﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using System.ServiceModel.Syndication;
using HtmlAgilityPack;

namespace ServeurRSS_1_0.Source.Model
{
    [DataContract]
    public class DataItem
    {
        [DataMember]
        public System.Guid id
        { get; set; }

        [DataMember]
        public System.Guid fk_id_Rss
        { get; set; }

        [DataMember]
        public string titre
        { get; set; }

        [DataMember]
        public string description
        { get; set; }

        [DataMember]
        public string link
        { get; set; }

        [DataMember]
        public string guid
        { get; set; }

        [DataMember]
        public string image
        { get; set; }

        [DataMember]
        public DateTime date
        { get; set; }

        [DataMember]
        public bool isRead
        { get; set; }

        [DataMember]
        public List<DataImage> media
        { get; set; }
    }

    [DataContract]
    public class DataImage
    {
        [DataMember]
        public System.Guid id
        { get; set; }

        [DataMember]
        public System.Guid fk_id_Items
        { get; set; }

        [DataMember]
        public string link
        { get; set; }

        [DataMember]
        public string type
        { get; set; }

        [DataMember]
        public string url
        { get; set; }
    }

    public class ItemModel : ParsingModel
    {
        static List<Image> formatList(IEnumerable<Image> listImg)
        {
            List<Image> test= listImg == null ? new List<Image>() : listImg.ToList<Image>();
            return test;
        }

        public bool getReadState(Guid idItem)
        {
            Guid? idUser = HttpContext.Current.Session["idUser"] as Guid?;
            if (idUser == null || idUser == Guid.Empty)
                throw new Exception("Unable to identified user");
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                UserItem userStateRead = db.UserItems.FirstOrDefault((p) => p.isRead == true && p.fk_id_User == idUser && p.fk_id_Items == idItem);
                if (userStateRead != null)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }

        }

        public List<DataItem> getItems(System.Guid idRss, int limit, int page)
        {
            //if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            //    throw (new Exception("Not Authenticate"));
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();



                var items = (from elem in db.Items
                             join img in db.Images on elem.id equals img.fk_id_Items
                             into listImg
                            where elem.fk_id_Rss == (System.Guid?)idRss
                            orderby elem.date descending
                            select new DataItem
                            {
                                id = elem.id,
                                guid = elem.guid != null ? elem.guid : "",
                                fk_id_Rss = elem.fk_id_Rss,
                                link = elem.link,
                                titre = elem.titre,
                                description = elem.description,
                                date = elem.date,
                                image = elem.imageUrl,
                                isRead = false,//getReadState(elem.id),
                                media = getListDataImage(formatList(listImg))
                            }).Skip(page * limit).Take(limit);
                return items.ToList<DataItem>();

            }
            catch (Exception e)
            {
                
                throw new Exception("Erreur getItems " + e, e);
            }
        }

        public string insertItemInDB(DataItem item)
        {
            if (item.date == null)
                item.date = DateTime.Now;
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                Item newItem = new Item
                {
                    id = item.id,
                    titre = item.titre,
                    description = item.description,
                    date = item.date,
                    guid = item.guid,
                    link = item.link,
                    fk_id_Rss = item.fk_id_Rss
                };
                db.Items.InsertOnSubmit(newItem);
                foreach (DataImage tmp in item.media)
                    tmp.fk_id_Items = item.id;
                if (item.media != null)
                    db.Images.InsertAllOnSubmit(getListItemImage(item.media));
                db.SubmitChanges();
            }
            catch (Exception e)
            {

                throw new Exception("Erreur insertItemInDB " + e, e);
            }
            return "OK";
        }

        public string insertListItemInDB(IEnumerable<DataItem> item)
        {
            int i = 0;
            try
            {
                foreach (DataItem tmp in item)
                {
                    i++;
                    insertItemInDB(tmp);
                }
            }
            catch (Exception e)
            {
                
                throw  new Exception(String.Format("Erreur insertListItemInDB item numero : {0}  ", i) + e, e);
            }
            return "OK";
        }

    public string insertListItemInDB(List<SyndicationItem> feddItems, System.Guid idRss)
        {   
           try
            {
               LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();
                List<Item> listItem = new List<Item>();
                string l;
                List<string> tmpL;
                List<Image> listImg = new List<Image>();
                foreach (SyndicationItem item in feddItems)
                {
                    if (item == null)
                        continue;
                    tmpL = getLinksAndType(item);
                    if (tmpL == null || tmpL.Count <= 0)
                    {
                        HtmlDocument doc = new HtmlDocument();
                        doc.LoadHtml(item.Summary.Text);
                        tmpL = getSrcImage(doc);
                    }
                    l = tmpL != null && tmpL.Count > 0 ? (tmpL[0].Contains(",") == true ?  tmpL[0].Split(new char[]{','})[0] : tmpL[0]) : "";
                    Item rssItemInsert = new Item
                    {
                        id = System.Guid.NewGuid(),
                        date = item.PublishDate != null ? item.PublishDate.DateTime :  DateTime.Now,
                        description = item.Summary != null ? getTextWithoutHtml(item.Summary.Text) : "",
                        fk_id_Rss = idRss,
                        guid = item.Id != null? item.Id : "" ,
                        imageUrl = l != null ? l : null,
                        link = item.SourceFeed != null && item.SourceFeed.BaseUri != null && item.SourceFeed.BaseUri.OriginalString != null ? item.SourceFeed.BaseUri.OriginalString : "",
                        titre = item.Title != null ? getTextWithoutHtml(item.Title.Text)   : ""               
                     };
                    //var entitySet = new EntitySet<Image>();
                    // entitySet.AddRange(getListImageSyndication(rssItemInsert.id, item));
                    // rssItemInsert.Images = entitySet;
                   listItem.Add(rssItemInsert);
                   listImg.AddRange(getListImageSyndication(rssItemInsert.id, item));
                }
                if (listItem != null)
                    db.Items.InsertAllOnSubmit<Item>(listItem);
                db.SubmitChanges();
                if (listImg != null)
                    db.Images.InsertAllOnSubmit<Image>(listImg);
                db.SubmitChanges();
            }
           catch (Exception e)
           {
               throw (new Exception("Erreur insertRssSyndication" + e.Message));
           } 
        return "OK";
        }
    public string eraseItem(System.Guid idItem)
        {
            try
            {
                LinkServeurRSSDataContext db = new LinkServeurRSSDataContext();

                db.Images.DeleteAllOnSubmit(db.Images.Where(p => p.fk_id_Items == idItem));
                db.Items.DeleteOnSubmit(db.Items.FirstOrDefault(p => p.id == idItem));
                db.SubmitChanges();
            }
            catch (Exception e)
            {

                throw new Exception("Erreur eraseItem "+ e, e);
            }

            return "OK";
        }

        public string eraseListItem(IEnumerable<DataItem> list)
        {
            int i = 0;
            try
            {
                foreach (DataItem tmp in list)
                {
                    i++;
                    eraseItem(tmp.id);
                }
            }
            catch (Exception e)
            {

                throw new Exception(String.Format("Erreur eraseListItem item numero : {0}  ", i) + e, e);
            }
            return "OK";

        }

        public Image getItemImage(DataImage img)
        {
            return new Image
            {
                fk_id_Items = img.fk_id_Items,
                id = img.id,
                link = img.link,
                url = img.url,
                type = img.type
            };
        }

        public DataImage getDataImage(Image img)
        {
            return new DataImage
            {
                fk_id_Items = img.fk_id_Items,
                id = img.id,
                link = img.link,
                url = img.url,
                type = img.type
            };
        }

        public List<DataImage> getListDataImage(List<Image> l)
        { 
            List<DataImage> res = new List<DataImage>();
            foreach (Image tmp in l)
                res.Add(getDataImage(tmp));
            return res;
        }
        public List<Image> getListItemImage(List<DataImage> l)
        {
            List<Image> res = new List<Image>();
            foreach (DataImage tmp in l)
                res.Add(getItemImage(tmp));
            return res;
        }
    }
}